#include "VideoManager.h"
#include "MApplication.h"
#include "GStreamer.h"
#include "VideoSettings.h"


Q_LOGGING_CATEGORY(VideoManagerLog, "VideoManagerLog")

VideoManager::VideoManager(QObject *parent)
    : QObject{parent}
{
    initVideo();
}

void VideoManager::initVideo()
{
    qDebug() << "--------- INIT VIDEO ----------- ";

    // 创建视频流接收器
    _videoReceiver[0] = GStreamer::createVideoReceiver(this);
    if (_videoReceiver[0] == nullptr) {
        qCDebug(VideoManagerLog) << "createVideoReceiver() failed";
    }

    // video streaming info
    QString rtspUri = "rtsp://127.0.0.1:8554/live/test";
    quint32 timeout = 0;
    quint32 cacheTime = 0;

    if (_videoReceiver[0]) {
        if (!rtspUri.isEmpty()) {
            // 接收器准备
            _videoReceiver[0]->start(rtspUri, timeout, 0, cacheTime);
        } else {
            qCDebug(VideoManagerLog) << "start receiver failed (url is empty)";
        }
    } else {
        qCDebug(VideoManagerLog) << "start receiver failed (receiver is null)";
    }
}

void VideoManager::startVideo()
{
    qDebug() << "--------- START VIDEO ----------- ";

    QQuickItem *root = qgcApp()->mainRootWindow();
    if (root == nullptr) {
        qCDebug(VideoManagerLog) << "mainRootWindow() failed. No root window";
        return;
    }
    // 获取Qml中主屏videoContent组件 (MVideoBackground)
    QQuickItem* widget = root->findChild<QQuickItem*>("videoContent");
    if (widget != nullptr && _videoReceiver[0] != nullptr) {
        // 创建主屏sink
        _videoSink[0] = GStreamer::createVideoSink(this, widget);
        if (_videoSink[0] != nullptr) {
            // 开始解码视频流并显示到组件中
            _videoReceiver[0]->startDecoding(_videoSink[0]);
        } else {
            qCDebug(VideoManagerLog) << "createVideoSink() failed";
        }
    } else {
        qCDebug(VideoManagerLog) << "video receriver is disabled";
    }
}
